<?php
/**
 * Created by JetBrains PhpStorm.
 * User: Administrator
 * Date: 12-9-1
 * Time: 下午9:45
 * To change this template use File | Settings | File Templates.
 */
class user extends MY_Model
{
    /**
     * 注册用户
     *
     * @param array $data
     * @return mixed
     */
    public function save(array $data)
    {
        $info = array(
            'username' => $data['username'],
            'password' => md5($data['password']),
            'email' => $data['email'],
            'source' => $data['source'],
            'create_time' => date('Y-m-d H:i:s'),
        );

        $this->db->insert('user', $info);
        return $this->db->insert_id();
    }

    /**
     * 获取用户信息
     *
     * @param $uId
     * @param string $fields
     * @param null $where
     * @return mixed
     */
    public function getUserById($uId, $fields = "*", $where = null)
    {
        //list($key, $fields) = self::formatField($fields);
        $this->db->select($fields)->from('user');
        $where && $this->db->where($where);
        if(is_array($uId))
        {
            return  $this->db->where_in('id', $uId)->get()->result_array();
        }
        return $this->db->where('id', $uId)->get()->row_array();
    }

    /**
     * 用户登陆
     *
     * @param $uName
     * @param $password
     * @return int
     * @notice 1 用户不存在, 2密码错误
     */
    public function userLogin($uName, $password)
    {
        //$uInfo = $this->getUserByName($uName);
        $uInfo = $this->db->select('id, username, password, email, source, create_time')->get_where('user', array('username' => $uName))->row_array();

        if (empty ($uInfo) || !is_array($uInfo)) {
            return 1;
        }

        if ($uInfo['password'] != md5(trim($password))) {
            return 2;
        }

        return $uInfo;
    }

    /**
     * @name 记录登陆日志
     *
     * @param $uId 用户ID
     * @param $ip 登陆IP地址
     * @param $source 登陆来源
     * @return boolean
     */
    public function record_login_log($uId, $ip, $source = 1)
    {
        $data = array(
            'uid' => $uId,
            'login_source' => $source,
            'ip' => $ip,
            'create_time' => date('Y-m-d H:i:s'),
        );

        $this->db->insert('user_login_log', $data);
        return $this->db->insert_id();
    }

    /**
     * @name 检测用户是否存在
     *
     * @param $uName 用户名
     * @return int
     */
    public function userNameIsExist($uName)
    {
        $this->db->from('user');
        $this->db->where("username = '{$uName}'");
        return $this->db->count_all_results();
    }
}
